

// Requires jQuery

// The class that makes handles scroll events, sending requests and updating new items

// The class that handles scroll events, sending requests and updating new items
function LazyLoader( params )
{
	this.updateUrl = function( url )
	{
		this._url = url;
	};

	this.updateData = function( data )
	{
		this._data = data;
	}
	
	this._bottomMargin = params[ 'bottomMargin' ]; // bottom from margin when start load new data

	this._showCallback = params[ 'showCallback' ];
	this._finishedCallback = params[ 'finishedCallback' ];

	var this2 = this;

	this._finished = false;

	this._gotPage = 1;

	var primaryPage; // used to restore the page (after reset)

	if( params[ 'next_page' ] != null ) // a current page
	{
		this._page = params[ 'next_page' ];
	}
	else
	{
		this._page = 2;
	}

	primaryPage = this._page

	this.reset = function()
	{
		this._page = primaryPage;
		this._finished = false;
		this._requestNext();
	};



	this.init = function()
	{
		var this2 = this;
		$( window ).scroll(	function() { this2._onScroll() }  );
		this._requestNext();
	};

	this._requestNext = function()
	{
		var data = this._data;
		data[ 'page' ] = this._page;

		this._page++;
		
		var this2 = this;

		this._waitUpdateMode = true;
		
		$.ajax(	{
					'url': this._url,
					'data': data,
					'dataType': 'json',
					'success': function( data ) { this2._success( data ); }
				} );
	};

	this._update = function()
	{
		this._showCallback( this._showData );
		this._requestNext();	
	};

	this._onScroll = function()
	{
		if( !this._waitUpdateMode )
		{		
			var scrollTop = $( window ).scrollTop();
			var windowHeight = $( window ).height();
			var sum = scrollTop + windowHeight + this._bottomMargin;
			var documentHeight = $( document ).height();
		
			if( sum > documentHeight )
			{
				if( !this._finished )
				{		
					if( this._gotPage + 1 >= this._page )
					{
						this._update();
					}
					else
					{
						this._waitUpdateMode = true;
					}
				}
			}
		}
	};

	this._success = function( resp )
	{
		this._showData = resp[ 'result' ];
		this._gotPage = parseInt( resp[ 'page' ] );	

		if( this._showData.length == 0 ) 
		{
			this._finished = true;
			this._finishedCallback();
		}

		this._waitUpdateMode = false;
	};
}